package com.zhuchaooasystem.ui.home.service;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.holder.DetailMaterialHolder;
import com.zhuchaooasystem.adapter.holder.DetialUnusualHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.ServiceDetailEntity;
import com.zhuchaooasystem.event.ServiceDetailEvent;
import com.zhuchaooasystem.presenter.home.servicedetail.ServiceDetailContract;
import com.zhuchaooasystem.presenter.home.servicedetail.ServiceDetailPresenter;
import com.zhuchaooasystem.ui.home.order.OrderDetailActivity;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.ScreenUtils;
import com.zhuchaooasystem.utils.ToastUtil;
import com.zhuchaooasystem.widget.StateButton;

import butterknife.BindView;
import butterknife.OnClick;

import static com.zhuchaooasystem.R.id.service_recyclerView;

public class ServiceDetailActivity extends BaseActivity<ServiceDetailPresenter> implements
        ServiceDetailContract.View {

    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_txt_title)
    TextView actionbarTxtTitle;
    @BindView(R.id.actionbar_iv_right)
    ImageView actionbarIvRight;
    @BindView(R.id.act_service_detail_radect_complete_layout)
    LinearLayout layout_redact_complelte;
    @BindView(R.id.service_detail_scroll)
    NestedScrollView scrollView;
    @BindView(R.id.actionbar_txt_right)
    TextView actionbarTxtRight;

    @BindView(R.id.act_setvice_detail_redact_image)
    ImageView actSetviceDetailRedactImage;
    @BindView(R.id.act_setvice_detail_redact_tv)
    TextView actSetviceDetailRedactTv;
    @BindView(R.id.act_service_detail_radect_layout)
    LinearLayout actServiceDetailRadectLayout;
    @BindView(R.id.act_setvice_detail_complete_image)
    ImageView actSetviceDetailCompleteImage;
    @BindView(R.id.act_setvice_detail_complete_tv)
    TextView actSetviceDetailCompleteTv;
    @BindView(R.id.act_service_detail_complete_layout)
    LinearLayout actServiceDetailCompleteLayout;
    @BindView(R.id.act_service_detail_code)
    TextView actServiceDetailCode;
    @BindView(R.id.act_service_detail_state)
    TextView actServiceDetailState;
    @BindView(R.id.act_service_detail_service_waring)
    TextView actServiceDetailServiceWaring;
    @BindView(R.id.act_service_detail_name)
    TextView actServiceDetailName;
    @BindView(R.id.act_service_detail_contact_name)
    TextView actServiceDetailContactName;
    @BindView(R.id.act_service_detail_reservation)
    TextView actServiceDetailReservation;
    @BindView(R.id.act_service_detail_phone)
    ImageView actServiceDetailPhone;
    @BindView(R.id.act_service_detail_address)
    TextView actServiceDetailAddress;
    @BindView(R.id.act_service_detail_livation)
    ImageView actServiceDetailLivation;

    @BindView(R.id.act_setvice_detail_delay_tv)
    TextView actSetviceDetailDelayTv;
    @BindView(R.id.act_setvice_detail_start_tv)
    TextView actSetviceDetailStartTv;
    @BindView(R.id.act_service_detail_order_detail_layout)
    LinearLayout actServiceDetailOrderDetailLayout;
    @BindView(R.id.act_service_detail_bule_circle_up)
    ImageView actServiceDetailBuleCircleUp;
    @BindView(R.id.act_service_detail_bule_circle_bottom)
    ImageView actServiceDetailBuleCircleBottom;
    @BindView(R.id.act_service_detail_sign_in)
    TextView actServiceDetailSignIn;
    @BindView(R.id.act_service_detail_sign_out)
    TextView actServiceDetailSignOut;
    @BindView(R.id.act_service_detail_txt_unusual_empty)
    TextView txt_unusual_empty;
    @BindView(service_recyclerView)
    EasyRecyclerView serviceRecyclerView;
    @BindView(R.id.act_service_detail_txt_edit_image)
    TextView edit_image;
    @BindView(R.id.act_service_detail_txt_edit_unusual)
    TextView edit_unusual;
    @BindView(R.id.act_service_detail_txt_material_empty)
    TextView txt_material_empty;
    @BindView(R.id.act_service_detail_recycle_material)
    EasyRecyclerView materialRecycle;
    @BindView(R.id.act_service_detail_state_btn_sign)
    StateButton actServiceDetailStateBtnSign;
    @BindView(R.id.activity_service_detail)
    RelativeLayout activityServiceDetail;
    @BindView(R.id.act_service_detail_schedule_layout)
    LinearLayout actServiceDetailScheduleLayout;

    //---------serviceModel
    @BindView(R.id.act_service_detail_early_start_time)
    TextView actServiceDetailEarlyStartTime;
    @BindView(R.id.act_service_detail_early_late_time)
    TextView actServiceDetailEarlyLateTime;
    @BindView(R.id.act_service_detail_start_time)
    TextView actServiceDetailStartTime;
    @BindView(R.id.act_service_detail_complete_time)
    TextView actServiceDetailCompleteTime;
    @BindView(R.id.act_service_detail_limit_time)
    TextView actServiceDetailLimitTime;
    @BindView(R.id.act_service_detail_sop_desc)
    TextView actServiceDetailSopDesc;
    @BindView(R.id.act_service_detail_reservation_time)
    TextView actServiceDetailServiceReservation;
    @BindView(R.id.act_service_detail_service_people)
    TextView actServiceDetailServicePeople;
    @BindView(R.id.act_service_detail_service_remark)
    TextView actServiceDetailServiceRemark;
    @BindView(R.id.act_service_detail_schedule_time_lenth)
    TextView actServiceDetailScheduleTimeLenth;
    @BindView(R.id.act_service_detail_sign_in_time)
    TextView actServiceDetailSignInTime;
    @BindView(R.id.act_service_detail_sign_out_time)
    TextView actServiceDetailSignOutTime;

    private String id;
    private String orderState;
    private String phone;
    private ServiceDetailEntity.ResultBean.SuccessfulBean bean;
    //----
    private RecyclerArrayAdapter unusualAdapter;
    private RecyclerArrayAdapter materialAdapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_service_detail;
    }

    @Override
    protected ServiceDetailPresenter getPresenter() {
        return new ServiceDetailPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        id = getIntent().getStringExtra(Key.ID);
        orderState = getIntent().getStringExtra("orderState");

    }

    @Override
    protected void initView() {
        actionbarIvBack.setVisibility(View.VISIBLE);
        actionbarTxtTitle.setText("服务详情");
        actServiceDetailStateBtnSign.setClickable(false);
        if (!orderState.equals("完成")) {
            actionbarIvRight.setImageResource(R.drawable.ic_three_point);
            actionbarIvRight.setVisibility(View.VISIBLE);
        }
        //-----
        serviceRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        DividerDecoration itemDecoration = new DividerDecoration(getResources().getColor(R.color.color_e1e1e1), ScreenUtils.dip2px(this, 1f), 0, 0);
        itemDecoration.setDrawLastItem(false);
        serviceRecyclerView.addItemDecoration(itemDecoration);
        serviceRecyclerView.setAdapterWithProgress(unusualAdapter = new RecyclerArrayAdapter<ServiceDetailEntity.ResultBean.SuccessfulBean.ExceptionModelBean>(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new DetialUnusualHolder(parent, ServiceDetailActivity.this);
            }
        });
        //-----
        materialRecycle.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        materialRecycle.setAdapterWithProgress(materialAdapter = new RecyclerArrayAdapter<ServiceDetailEntity.ResultBean.SuccessfulBean.MaterialBean>(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new DetailMaterialHolder(parent, ServiceDetailActivity.this);
            }
        });
        materialRecycle.setHorizontalScrollBarEnabled(false);

        mPresenter.downServiceDetailData(id);
//        mPresenter.downServiceCardsInfo(id);

        //RxBus注册，和eventbus一样需要注册
        RxBus.get().register(this);
    }

    @Override
    protected void initDataAndLoadData() {

    }


    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_iv_right, R.id.act_service_detail_phone,
            R.id.act_service_detail_livation, R.id.act_service_detail_schedule_layout,
            R.id.act_service_detail_radect_layout, R.id.act_service_detail_complete_layout
            , R.id.act_service_detail_state_btn_sign, R.id.act_service_detail_txt_edit_unusual
            , R.id.act_service_detail_txt_edit_image, R.id.act_service_detail_order_detail_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.actionbar_iv_back:

                ServiceDetailActivity.this.finish();

                break;
            //标题栏右侧
            case R.id.actionbar_iv_right:
                if (layout_redact_complelte.isShown()) {
                    layout_redact_complelte.setVisibility(View.GONE);

                } else {
                    layout_redact_complelte.setVisibility(View.VISIBLE);
                }
                break;
            //打电话
            case R.id.act_service_detail_phone:

                Intent intent = new Intent(Intent.ACTION_DIAL,
                        Uri.parse("tel:" + phone));
                //如果是安卓6.0的系统  打电话的权限没有打开
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    //请求权限
                    requestPermission(new String[]{Manifest.permission.CALL_PHONE}, Key.CALL_PHONE);
                } else {
                    startActivity(intent);
                }

                break;
            //定位
            case R.id.act_service_detail_livation:
                Bundle data = new Bundle();
                data.putString("address", bean.getAnonymousModel().getAddress());
                AppUtils.jump(mContext, ServiceAddMapActivity.class, data);
                break;
            //查看服务进度
            case R.id.act_service_detail_schedule_layout:

                Intent intent_schedule = new Intent(ServiceDetailActivity.this, ServiceScheduleActivity.class);
                Bundle bundle_schedule = new Bundle();
                bundle_schedule.putSerializable(Key.SERVICE_DETAIL_ENTITY, bean);
                intent_schedule.putExtras(bundle_schedule);
                startActivity(intent_schedule);
                break;
            //编辑
            case R.id.act_service_detail_radect_layout:
                Intent intent_radect = new Intent(ServiceDetailActivity.this, ServiceRadectActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Key.SERVICE_DETAIL_ENTITY, bean);
                intent_radect.putExtras(bundle);
                startActivity(intent_radect);
                break;
            //完成
            case R.id.act_service_detail_complete_layout:
                mPresenter.finishService(bean.getAnonymousModel().getID());
                break;
            //打卡
            case R.id.act_service_detail_state_btn_sign:
                if (actServiceDetailStateBtnSign.isClickable()) {
                    Bundle data1 = new Bundle();
                    data1.putInt("serviceid", bean.getAnonymousModel().getID());
                    AppUtils.jump(mContext, ServiceSignActivity.class, data1);
                }
                break;
            //上传图片编辑
            case R.id.act_service_detail_txt_edit_image:
                Bundle dataImage = new Bundle();
                if (edit_image.getText().toString().equals("编辑")) {
                    dataImage.putBoolean("canEdit", true);
                } else {
                    dataImage.putBoolean("canEdit", false);
                }
                dataImage.putInt("projectId", bean.getAnonymousModel().getID());
                dataImage.putString("orderCode", bean.getAnonymousModel().getOrderCode());
                AppUtils.jump(mContext, ServiceImageActivity.class, dataImage);
                break;
            //异常说明编辑
            case R.id.act_service_detail_txt_edit_unusual:
                Bundle dataUnusual = new Bundle();
                if (edit_unusual.getText().toString().equals("编辑")) {
                    dataUnusual.putBoolean("canEdit", true);
                } else {
                    dataUnusual.putBoolean("canEdit", false);
                }
                dataUnusual.putInt("projectId", bean.getAnonymousModel().getID());
                dataUnusual.putString("orderCode", bean.getAnonymousModel().getOrderCode());
                AppUtils.jump(mContext, ServiceUnusualActivity.class, dataUnusual);
                break;
            //查看订单详情
            case R.id.act_service_detail_order_detail_layout:

                Intent intent_order_detail = new Intent(ServiceDetailActivity.this, OrderDetailActivity.class);
                intent_order_detail.putExtra(Key.ORIDERID, bean.getAnonymousModel().getOrderid() + "");
                startActivity(intent_order_detail);

                break;
        }
    }

    @Override
    public void showAnonymousData(ServiceDetailEntity.ResultBean.SuccessfulBean entity) {
        scrollView.setVisibility(View.VISIBLE);
        bean = entity;

        phone = entity.getAnonymousModel().getPhone();

        if (entity.getAnonymousModel().getServiceStatus().equals("完成")) {
            edit_image.setText("查看");
            edit_unusual.setText("查看");
            actionbarIvRight.setVisibility(View.GONE);
        } else {
            actionbarIvRight.setImageResource(R.drawable.ic_three_point);
            actionbarIvRight.setVisibility(View.VISIBLE);
            edit_image.setText("编辑");
            edit_unusual.setText("编辑");
        }
        actServiceDetailCode.setText(id + "");
        actServiceDetailServiceWaring.setText(entity.getAnonymousModel().getCreatetime());
        actServiceDetailState.setText(entity.getAnonymousModel().getServiceStatus());
        actServiceDetailName.setText(entity.getAnonymousModel().getServerName());
        actServiceDetailContactName.setText(entity.getAnonymousModel().getContactName());
        actServiceDetailReservation.setText(entity.getAnonymousModel().getPhone());
        actServiceDetailAddress.setText(entity.getAnonymousModel().getAddress());

    }

    @Override
    public void showServiceData(ServiceDetailEntity.ResultBean.SuccessfulBean entity) {
        actServiceDetailEarlyStartTime.setText("最早开始时间：" + entity.getServiceModel().getTheFirst());
        actServiceDetailEarlyLateTime.setText("最晚开始时间：" + entity.getServiceModel().getThelatest());
        if (entity.getAnonymousModel().getServiceStatus().equals("开始")) {
            actServiceDetailStartTime.setVisibility(View.VISIBLE);
            actServiceDetailStartTime.setText("开始时间：" + entity.getServiceModel().getTartTodoTime());
        } else if (entity.getAnonymousModel().getServiceStatus().equals("完成")) {
            actServiceDetailStartTime.setVisibility(View.VISIBLE);
            actServiceDetailStartTime.setText("开始时间：" + entity.getServiceModel().getTartTodoTime());
            actServiceDetailCompleteTime.setVisibility(View.VISIBLE);
            actServiceDetailCompleteTime.setText("完成时间：" + entity.getServiceModel().getEdnTodoTime());
        }

        actServiceDetailLimitTime.setText("工期：" + entity.getServiceModel().getSop_time() + "天");
        actServiceDetailSopDesc.setText(entity.getServiceModel().getSop_desc());
        actServiceDetailServiceReservation.setText("预约时间：" + entity.getServiceModel().getReservation());
        actServiceDetailServicePeople.setText("服务人：" + entity.getServiceModel().getServicePeople());
        //如果没有备注则设置为空
        if (entity.getServiceModel().getServiceRemark() == null ||
                entity.getServiceModel().getServiceRemark().equals("")) {
            actServiceDetailServiceRemark.setText("服务备注：" + "无");

        } else {
            actServiceDetailServiceRemark.setText("服务备注：" + entity.getServiceModel().getServiceRemark());

        }
        actServiceDetailScheduleTimeLenth.setText("共计" + entity.getServiceModel().getSchedule() + "个服务" + " | " +
                "共计" + entity.getServiceModel().getTimeLength() + "天");
        //总体进展
        actSetviceDetailDelayTv.setText("总体进展：" + entity.getServiceModel().getServicrItem().getSop_WorkDays());
        actSetviceDetailStartTv.setText(entity.getServiceModel().getServicrItem().getSop_WotkMsg());

        //还需要判断 进行中任务---开始时间的显示隐藏


    }

    @Override
    public void showExceptionData(ServiceDetailEntity.ResultBean.SuccessfulBean entity) {
        if (null != entity.getExceptionModel() && entity.getExceptionModel().size() > 0) {
            unusualAdapter.clear();
            unusualAdapter.addAll(entity.getExceptionModel());
            serviceRecyclerView.setVisibility(View.VISIBLE);
            txt_unusual_empty.setVisibility(View.GONE);
        } else {
            txt_unusual_empty.setVisibility(View.VISIBLE);
            serviceRecyclerView.setVisibility(View.GONE);
        }
    }

    /**
     * 图片
     *
     * @param entity
     */
    @Override
    public void showMaterialData(ServiceDetailEntity.ResultBean.SuccessfulBean entity) {

        if (null != entity.getMaterial() && entity.getMaterial().size() > 0) {
            materialAdapter.clear();
            materialAdapter.addAll(entity.getMaterial());
            materialRecycle.setVisibility(View.VISIBLE);
            txt_material_empty.setVisibility(View.GONE);
        } else {
            txt_material_empty.setVisibility(View.VISIBLE);
            materialRecycle.setVisibility(View.GONE);
        }
    }

    /**
     * 签到
     *
     * @param entity
     */
    @Override
    public void showCardsInfoData(ServiceDetailEntity.ResultBean.SuccessfulBean entity) {
        actServiceDetailSignIn.setText(entity.getCardsInfo().getPunchCardAreaOne());
        if (!TextUtils.isEmpty(entity.getCardsInfo().getPunchCardTimeOne())) {
            actServiceDetailSignInTime.setText("【" + entity.getCardsInfo().getPunchCardTimeOne() + "】");
        }
        actServiceDetailSignOut.setText(entity.getCardsInfo().getPunchCardAreaTwo());
        if (!TextUtils.isEmpty(entity.getCardsInfo().getPunchCardTimeTwo())) {
            actServiceDetailSignOutTime.setText("【" + entity.getCardsInfo().getPunchCardTimeTwo() + "】");
        }

        if (!entity.getAnonymousModel().getServiceStatus().equals("完成")) {
            if (TextUtils.isEmpty(entity.getCardsInfo().getCardStatusOne()) || TextUtils.isEmpty(entity.getCardsInfo().getCardStatusTwo())) {
                actServiceDetailStateBtnSign.setNormalBackgroundColor(getResources().getColor(R.color.color_1bc3ad));
                actServiceDetailStateBtnSign.setPressedBackgroundColor(getResources().getColor(R.color.color_901bc3ad));
                actServiceDetailStateBtnSign.setClickable(true);
            } else {
                actServiceDetailStateBtnSign.setNormalBackgroundColor(getResources().getColor(R.color.color_bfbfbf));
                actServiceDetailStateBtnSign.setPressedBackgroundColor(getResources().getColor(R.color.color_D5D5D5));
                actServiceDetailStateBtnSign.setClickable(false);
            }
        } else {
            actServiceDetailStateBtnSign.setNormalBackgroundColor(getResources().getColor(R.color.color_bfbfbf));
            actServiceDetailStateBtnSign.setPressedBackgroundColor(getResources().getColor(R.color.color_D5D5D5));
            actServiceDetailStateBtnSign.setClickable(false);
        }
    }

    @Override
    public void setClickable(boolean clickable) {
        actServiceDetailCompleteLayout.setClickable(clickable);
    }

    @Override
    public void finishService() {
        ToastUtil.showShort(mContext, "任务已完成");
        actionbarIvRight.setVisibility(View.GONE);
        layout_redact_complelte.setVisibility(View.GONE);
        mPresenter.downServiceDetailData(id);
        RxBus.get().post("RedactToService", new BaseEvent<>());
    }

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);

        switch (requestCode) {
            case Key.CALL_PHONE:

                Intent intent = new Intent(Intent.ACTION_DIAL,
                        Uri.parse("tel:" + phone));
                startActivity(intent);

                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 这是在主线程处理接收到的数据
     * <p>
     * RedactToDetail这个是你发送通知的时候，自定义的标志，用来识别通知
     * <p>
     * 编辑服务以后  服务详情页应该刷新
     *
     * @param btnEvent
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag("RedactToDetail")
            }

    )
    /**
     * 这个方法名和自定义的标志名一致，用来处理接收到的数据，其实rxbus的用法和eventbus用发基本是一样的
     */
    public void RedactToDetail(ServiceDetailEvent btnEvent) {
        mPresenter.downServiceDetailData(id);
//        mPresenter.downServiceCardsInfo(id);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("RedactFinish")})
    public void RedactFinish(BaseEvent btnEvent) {
        if (layout_redact_complelte.isShown()) {
            layout_redact_complelte.setVisibility(View.GONE);
        }
        mPresenter.downServiceDetailData(id);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("reservation")})
    public void reservation(BaseEvent event) {
        RxBus.get().post("RedactToService", new BaseEvent<>());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //RxBus解除注册，防止内存泄露
        RxBus.get().unregister(this);
    }
}
